import { HttpCode } from '#/utils/contacts';
import { TRMessage } from '#/components';
import {
  enableAI,
  historyChartService,
  postAdjustProportionData,
  postQueryForecastAndSimulate,
  postQueryRateData,
  queryForecastAndManualStrategy,
  tianjiChartService,
} from './service';
import _ from 'lodash';
import { getBaseKeys, getXAxisData, powerAdjustBaseOptions, priceDiffBaseOptions } from './helper';

export default {
  namespace: 'shortTermForecastingRedesignV2',
  state: {
    searchForm: {
      // quantityQuotation: 1, // 除新疆能选报量报价其他都是报量不报价
      // calendarDate: moment().add(1, 'days').format('YYYY-MM-DD'),
      // marketId: 'PHBSX',
      // provinceId: '14',
      // stationId: '14083003',
      // saveType: 1,
    },
    // 价差loading
    priceLoading: false,
    // 价差数据图
    priceChartData: {},
    // 功率预测调整图Loading
    predictionAdjustmentLoading: false,
    // 功率预测调整图
    predictionAdjustment: {},
    // Ai策略图loading
    aiAdjustmentLoading: false,
    // 人工智能策略图数据
    aiAdjustmentChartData: {},
    // 策略编辑表格数据loading
    dataListLoading: false,
    // 策略编辑表格数据
    dataList: [],
    // 策略编辑表格基准预测源下拉列表
    dataSourceList: [],
    // form表单的表格数据
    tableData: {},
    // 策略类型 'kalman', // MODEL 1
    // 'gaussian', // MODEL 2
    // 'none', // 不平滑
    smoothStatus: 'gaussian',
    // 策略引用的stationId
    quoteStationId: null,
    // 是否考虑储能（ 1 考虑储能  0不考虑储能） 默认0
    store: 0,
    // Ai策略开关
    openAi: 0,
    // 申报计划表格数据
    issuePlanTableData: [],
    // 保存按钮禁用
    saveButtonDisabled: false,
    // 默认基准数据源Id
    defaultDataSourceId: '',
    // 默认最大值
    defaultCapacity: '',
  },
  reducers: {
    setState(state, { payload }) {
      return { ...state, ...payload };
    },
    setIssuePlanTableData(state, { payload }) {
      return { ...state, ...payload };
    },
  },
  effects: {
    // 获取天机预测
    *getTianjiChart({ payload }, { call, put, select }) {
      yield put({
        type: 'setState',
        payload: {
          priceLoading: true,
        },
      });
      const res = yield call(tianjiChartService, {
        ...payload,
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        const data = res?.spotPriceDataMap?.clearDifferencePriceForecast || {};
        yield put({
          type: 'setState',
          payload: {
            priceChartData: {
              ...priceDiffBaseOptions,
              xAxis: [
                {
                  type: 'category',
                  data: getXAxisData(payload?.calendarDate, data.xAxis),
                },
                {
                  gridIndex: 1,
                  type: 'category',
                  data: getXAxisData(payload?.calendarDate, data.xAxis),
                  show: false,
                },
              ],
              series: [
                {
                  data: data?.dayAheadPriceForecast || [],
                  type: 'line',
                  name: '现货日前价预测',
                  color: '#5E92F6',
                  props: {
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                  },
                },
                {
                  data: data?.realtimePriceForecast || [],
                  type: 'line',
                  name: '现货实时价预测',
                  color: '#E86452',
                  props: {
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                  },
                },
                {
                  data: data?.priceDifferenceForecast || [],
                  type: 'line',
                  name: '现货实时日前价差',
                  color: '#F5BE15',
                  props: {
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                  },
                },
                {
                  data:
                    data?.priceDifferenceConfidence?.map((i) =>
                      i !== '-' ? Math.floor(i * 100) : i,
                    ) || [],
                  type: 'bar',
                  name: '价差置信度',
                  color: '#434E62',
                  props: {
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                  },
                },
              ],
            },
          },
        });
      } else {
        TRMessage.error(res?.message || '获取天机预测数据失败!');
        yield put({
          type: 'setState',
          payload: {
            priceChartData: {},
          },
        });
      }
      yield put({
        type: 'setState',
        payload: {
          priceLoading: false,
        },
      });
    },

    // 获取历史预测
    *getHistoryChart({ payload }, { call, put, select }) {
      yield put({
        type: 'setState',
        payload: {
          priceLoading: true,
        },
      });
      const res = yield call(historyChartService, {
        ...payload,
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        const data = res?.data.baseAfter || {};
        yield put({
          type: 'setState',
          payload: {
            priceChartData: {
              ...priceDiffBaseOptions,
              xAxis: [
                {
                  type: 'category',
                  data: getXAxisData(payload?.calendarDate, res?.data.xAxis),
                },
                {
                  gridIndex: 1,
                  type: 'category',
                  data: getXAxisData(payload?.calendarDate, res?.data.xAxis),
                  show: false,
                },
              ],
              series: [
                {
                  data: data?.dayAheadPrice || [],
                  type: 'line',
                  name: '现货日前价预测',
                  color: '#5E92F6',
                  props: {
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                  },
                },
                {
                  data: data?.realTimePrice || [],
                  type: 'line',
                  name: '现货实时价预测',
                  color: '#E86452',
                  props: {
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                  },
                },
                {
                  data: data?.dayAheadPriceDiff || [],
                  type: 'line',
                  name: '现货实时日前价差',
                  color: '#F5BE15',
                  props: {
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                  },
                },
                {
                  data: data?.basePersent?.map((i) => (i !== '-' ? i * 100 : i)) || [],
                  type: 'bar',
                  name: '价差置信度',
                  color: '#434E62',
                  props: {
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                  },
                },
              ],
            },
          },
        });
      } else {
        yield put({
          type: 'setState',
          payload: {
            priceChartData: {},
          },
        });
        TRMessage.error(res?.message || '获取天机预测数据失败!');
      }
      yield put({
        type: 'setState',
        payload: {
          priceLoading: false,
        },
      });
    },

    // 获取功率预测调整
    *getPowerPredictionAdjustment({ payload }, { call, put, select }) {
      if (
        payload?.dataList?.length !== 0 &&
        payload?.dataList?.every(
          (i) =>
            i.beginIndex !== null &&
            i.beginIndex !== undefined &&
            i.endIndex !== null &&
            i.endIndex !== undefined,
        )
      ) {
        yield put({
          type: 'setState',
          payload: {
            predictionAdjustmentLoading: true,
          },
        });
        const res = yield call(postQueryForecastAndSimulate, {
          ...payload,
        });
        if (res?.statusCode === HttpCode.SUCCESS) {
          const data = res?.data || {};
          const keys = getBaseKeys(data);
          const series = keys.map((k) => {
            const arr = data?.[k + 'Values'] || [];
            const name = data?.[k + 'Source'];
            const color = data?.[k + 'Colour'];
            return {
              data: arr,
              type: name === '市场化中长期' ? 'bar' : 'line',
              name,
              color,
              ...{
                ...(name === '市场化中长期'
                  ? {
                      props: {
                        lineStyle: {
                          type: 'dashed',
                        },
                      },
                    }
                  : {}),
              },
            };
          });
          yield put({
            type: 'setState',
            payload: {
              predictionAdjustment: {
                ...powerAdjustBaseOptions,
                xAxis: [
                  {
                    type: 'category',
                    data: getXAxisData(payload?.markDate, data.xAxis),
                  },
                ],
                series,
              },
            },
          });
        } else {
          yield put({
            type: 'setState',
            payload: {
              predictionAdjustment: {},
            },
          });
          TRMessage.error(res?.message || '获取功率预测调整失败!');
        }
        yield put({
          type: 'setState',
          payload: {
            predictionAdjustmentLoading: false,
          },
        });
      }
    },

    // 获取调整策略编辑列表数据
    *getQueryRateData({ payload }, { call, put, select }) {
      let state = yield select((_) => _.shortTermForecastingRedesignV2);
      const { searchForm } = state;
      yield put({
        type: 'setState',
        payload: {
          dataListLoading: true,
        },
      });
      const res = yield call(postQueryRateData, {
        ...payload,
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        const list = _.get(res, 'data.dataList', []);
        yield put({
          type: 'setState',
          payload: {
            defaultDataSourceId: res.data.defaultDataSourceId,
            defaultCapacity: res.data.defaultCapacity,
            dataList: list,
            dataSourceList: _.get(res, 'data.dataSourceList', []).map((i) => ({ ...i })),
            smoothStatus: _.get(res, 'data.smoothStatus', 'gaussian'),
          },
        });
        const powerParams = {
          markDate: searchForm.calendarDate,
          stationId: searchForm.stationId,
          marketId: searchForm.marketId,
          saveType: searchForm.saveType,
          dataList: list,
          store: state.store,
          quoteStationId: state.quoteStationId ?? null,
          smoothStatus: state.smoothStatus ?? null,
          // 数据来源(1:HDPSS,2:HDPS,3:LP,4:PFDS,5:启用AI,6:人工)
          dataFrom: state.openAi ? 5 : 6, // （8, "-启用AI" \ 9, "-人工"）
        };
        // 获取功率预测调整
        yield put({
          type: 'shortTermForecastingRedesignV2/getPowerPredictionAdjustment',
          payload: powerParams,
        });
      } else {
        TRMessage.error(res?.message || '获调整策略失败!');
      }
      yield put({
        type: 'setState',
        payload: {
          dataListLoading: false,
        },
      });
    },

    // 获取人工智能策略图数据
    *getAiAdjustmentChartData({ payload }, { call, put, select }) {
      if (
        payload?.dataList?.length !== 0 &&
        payload?.dataList?.every((i) => i.beginTime && i.endTime)
      ) {
        yield put({
          type: 'setState',
          payload: {
            aiAdjustmentLoading: true,
          },
        });
        const res = yield call(queryForecastAndManualStrategy, payload);
        if (res?.statusCode === HttpCode.SUCCESS) {
          const data = res?.data || {};
          const keys = getBaseKeys(data);
          const series = keys.map((k) => {
            const arr = data?.[k + 'Values'] || [];
            const name = data?.[k + 'Source'];
            const color = data?.[k + 'Colour'];
            return {
              data: arr,
              type: 'line',
              name,
              color,
            };
          });
          yield put({
            type: 'setState',
            payload: {
              aiAdjustmentChartData: {
                ...powerAdjustBaseOptions,
                xAxis: [
                  {
                    type: 'category',
                    data: getXAxisData(payload?.markDate, data.xAxis),
                  },
                ],
                series,
              },
            },
          });
        } else {
          yield put({
            type: 'setState',
            payload: {
              aiAdjustmentChartData: {},
            },
          });
          TRMessage.error(res?.message || '查询失败!');
        }
        yield put({
          type: 'setState',
          payload: {
            aiAdjustmentLoading: false,
          },
        });
      }
    },

    // 人工策略AI策略启用数据
    *getAiTableData({ payload }, { call, put, select }) {
      let state = yield select((_) => _.shortTermForecastingRedesignV2);
      const res = yield call(enableAI, {
        markDate: state.searchForm.calendarDate,
        smoothStatus: state.smoothStatus,
        stationId: state.searchForm.stationId,
        marketId: state.searchForm.marketId,
        store: state.store,
      });
      if (res?.statusCode === HttpCode.SUCCESS) {
        yield put({
          type: 'setState',
          payload: {
            dataList: res?.dataList || [],
          },
        });
      } else {
        TRMessage.error(res?.message || '查询失败!');
      }
    },

    // 保存调整策略编辑列表数据(报量不报价）
    *saveAdjustTableData({ payload }, { call, put, select }) {
      let state = yield select((_) => _.shortTermForecastingRedesignV2);
      yield put({
        type: 'setState',
        payload: {
          dataListLoading: true,
        },
      });
      const { searchForm } = state;
      const res = yield call(postAdjustProportionData, payload);
      if (res?.statusCode === HttpCode.SUCCESS) {
        yield put({
          type: 'getQueryRateData',
          payload: {
            provinceId: searchForm.provinceId,
            stationId: searchForm.stationId,
            quantityQuotation: 1,
            reset: 0,
            saveType: searchForm.saveType,
            marketId: searchForm.marketId,
            calendarDate: searchForm.calendarDate,
          },
        });
      } else {
        TRMessage.error(res?.message || '保存失败!');
      }
      yield put({
        type: 'setState',
        payload: {
          dataListLoading: false,
        },
      });
    },
  },
};
